import axios from 'axios';
import router from '../router/pc/index';
import {paramsQs} from '@/utils/index';
import {Message, Loading} from 'element-ui';
import { downloadFile } from '@/utils/index';

const AXIOSTIME = 15000;  // 请求超时时间
const BASE_URL = process.env.VUE_APP_API; // 环境对应的api
// http 状态码
const ERROR_CODE = {
  400: '错误请求',
  401: '会话过期',
  403: '拒绝访问',
  404: '请求错误,未找到该资源',
  405: '请求方法未允许',
  408: '请求超时',
  500: '网络连接到服务器失败',
  501: '网络未实现',
  502: '网络错误',
  503: '服务不可用',
  504: '网络超时',
  505: 'http版本不支持该请求',
};

const startLoading = () => {
  return Loading.service({
    lock: true,
    text: '加载中……',
    target: document.body,
    background: 'rgba(0, 0, 0, 0.5)'
  });
};

const Instance = axios.create({
  baseURL : process.env.VUE_APP_API,
  timeout: AXIOSTIME
});

localStorage.setItem('BASE_URL', BASE_URL);
Instance.defaults.timeout = AXIOSTIME;
Instance.defaults.withCredentials = false;
Instance.defaults.crossDomain = true;

// request 拦截器
Instance.interceptors.request.use(
  config => {
    const token = window.localStorage.getItem('token'); //  注意使用的时候需要引入cookie方法
    config.data = JSON.stringify(config.data);
    config.headers = {
      'Content-Type': 'application/json;charset=utf-8;application/vnd.ms-excel',
      'Accept': '*/*',
      'token': token,
      ...config.headers
    };
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// response 拦截器
Instance.interceptors.response.use(
  response => {
    const {
      data: {
        message,
        code
      } = {}
    } = response;
    if (code && (code !== 0 && code !== 200) ) {
      // 统一报错
      Message.warning(message);
    }
    return response;
  },
  error => {
    if (error && error.response) {
      const status = error.response.status;

      if (status == 401) {
        router.push({name: 'login'});
      } else if (status == 500) {
        Message.warning(error.response.data.message);
      } else {
        // 统一错误提示
        error.message = Object.keys(ERROR_CODE).includes(status) ? ERROR_CODE[status] : `连接错误${error.response.status}`;
        Message.warning(error.message);
      }

    } else {
      Message.warning('网络连接到服务器超时，请联系管理员');
    }
    return Promise.reject(error);
  }
);

const $https = {};
const methods = ['get', 'post', 'patch', 'put', 'delete'];
for (let i of methods) {
  $https[i] = function (url, params = {}, loading = false) {
    return new Promise((resolve, reject) => {
      let $loading = null;
      loading && ($loading = startLoading());
      // get 请求，参数序列化
      if (i == 'get') {
        const pm = paramsQs(params);
        Instance.get(`${url}?${pm}`).then(res => {
          loading && $loading.close();
          resolve(res.data);
        }).catch(err => {
          reject(err);
          $loading && $loading.close();
        });
      } else {
        Instance[i](url, params).then(res => {
          loading && $loading.close();
          resolve(res.data);
        }).catch(err => {
          reject(err);
          $loading && $loading.close();
        });
      }
    });
  };
}

export default $https;

// excel导出
export function downloadFn (url, params, fileName, callBack) {
  let token = window.localStorage.getItem('token');
  return axios({
    url,
    baseURL: BASE_URL,
    method: 'post',
    data: params,
    defaults: {
      withCredentials: true,
      crossDomain: true
    },
    responseType: 'arraybuffer',
    headers: {
      ...{},
      token
    }
  }).then(res => {
    downloadFile(res.data, fileName);
    // Message.success('导出成功');
    callBack && callBack(res);
  });
}
